/*
 * Copyright 2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dopdf.utils;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * The class that implements a simple LRU cache.
 *
 * @param <K> the type of key that will be held by this LRU cache.
 * @param <V> the type of value held by this LRU cache.
 * @author Deep Shah
 */
public class LRUCache<K, V> {

    /** The backing linked hash map object that will implement the LRU algorithm for us. */
    private static final LinkedHashMap cache = new LinkedHashMap(Constants.Cache.MAX_CAPACITY,
            Constants.Cache.LOAD_FACTOR, true) {

        /**
         * {@inheritDoc}
         */
        @Override
        protected boolean removeEldestEntry(final Map.Entry eldest) {
            return size() > Constants.Cache.SIZE;
        }
    };

    /**
     * Puts the key value pair in the LinkedHashmap.
     * @param key the key value to put in the map.
     * @param value the value to put in the map.
     */
    public void put(final K key, final V value) {
        cache.put(key, value);
    }

    /**
     * The method that gets the value from the LRU cache for the given key.  If the value is not found null is returned.
     * @param key the key for which we have to find the value in the cache.
     * @return The value matching the passed in key.  Null if no match is found.
     */
    public V get(final K key) {
        return (V) cache.get(key);
    }

    /**
     * The method that returns true if the cache holds the given key.
     * @param key the key which we have to find in the cache.
     * @return true if the value against the given key is found, false otherwise.
     */
    public boolean containsKey(final K key) {
        return cache.containsKey(key);
    }
}
